package com.itheima.filter;

import com.itheima.common.constants.SystemConstants;
import com.itheima.common.util.AppJwtUtil;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.ExpiredJwtException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;
@Component
/**
 * 配置自媒体的全局过滤器
 */
@Slf4j
public class WemediaFilter implements GlobalFilter , Ordered {
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        //获取请求和响应数据对象
        ServerHttpRequest req = exchange.getRequest();
        ServerHttpResponse resp = exchange.getResponse();
        //获取请求路径进行过滤
        String path = req.getURI().getPath();
        //判断请求路径是否包含直接放行的数据
        if (path.startsWith("/wemedia/login")){
            return chain.filter(exchange);
        }
        //没有直接放行的请求路径，获取请求头数据，根据请求头中token判断是否登录，登录则直接放行
        HttpHeaders headers = req.getHeaders();
        String token = headers.getFirst("token");
        //判断token是否是有效，有效则直接放行，无效则返回友好提示
        /*if (AppJwtUtil.verifyToken(token) == 1){
            return chain.filter(exchange);
        }*/
        try {
            Claims claims = AppJwtUtil.getClaimsBody(token);
            if (claims != null) {
                //token有效获取token中的userId放入请求头中
                Long id = claims.get("id",Long.class);
                //调用请求头对象将获取的userId放到请求文件管理微服务的请求头中
                //因为网关微服务的服务是netty文件上传微服务是tomcat所以要使用mutate进行转换
                req.mutate().header("userId",id.toString());
                return chain.filter(exchange);
            }

        } catch (ExpiredJwtException ex) {
            log.error("token超时",ex);
        } catch (Exception e) {
            log.error("权限不足,非法token",e);
        }
        //没有登录或是，token失效则响应401状态码
        resp.setStatusCode(HttpStatus.UNAUTHORIZED);
        return resp.setComplete();
    }

    @Override
    public int getOrder() {
        return 0;
    }
}
